package com.happy3w.ssp.schoolmatehome.controller;

import com.happy3w.ssp.schoolmatehome.entity.ChatSessionEntity;
import com.happy3w.ssp.schoolmatehome.exception.MessageException;
import com.happy3w.ssp.schoolmatehome.interceptor.AttributeKeys;
import com.happy3w.ssp.schoolmatehome.repository.ChatSessionRepository;
import com.happy3w.ssp.schoolmatehome.service.auth.TheUserDetail;
import lombok.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/chat-session")
public class ChatController {
    private final ChatSessionRepository chatSessionRepository;

    @PostMapping()
    public void saveChatSession(@RequestBody ChatSessionReq req, @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        chatSessionRepository.save(ChatSessionEntity.builder()
                .userId(userDetail.getUser().getId())
                .sessionId(req.sessionId).
                build());
    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class ChatSessionReq {
        private String sessionId;
    }

    @PostMapping("/query")
    public Set<String> getUserSessionsByTime(@RequestBody GetChatMessageReq req, @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        List<ChatSessionEntity> sessions = chatSessionRepository.findByUserIdAndCreatedAtBetween(
                userDetail.getUser().getId(),
                new Date(req.getStartTime()),
                new Date(req.getEndTime()));

        return sessions.stream()
                .map(ChatSessionEntity::getSessionId)
                .collect(Collectors.toSet());
    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class GetChatMessageReq {
        private Long startTime;
        private Long endTime;
    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ChatMessageResponse {
        private List<ChatMessage> messages;
        // 根据实际API响应结构调整
    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ChatMessage {
        private String id;
        private String content;
        private String sessionId;
        // 其他字段根据实际API定义
    }

}
